//
//  AddMedicine.m
//  Pocket Doctor alpha version
//
//  Created by Sherif, Yin, Taylor, Jacob, Anna, Mike on 11-10-25.
//  Copyright (c) 2011 __Sytjam__. All rights reserved.
//
//Class Description: Adding all the medication requirements and times.
//                   Creates notifications on save.
//
//Known Bugs: none.
//some medicines in database have '?' in their names - ? should be replaced with "i" - example: 02237179
//logChange into database
//refillable still doesnt work

#import "AddMedicine.h"
#import "MedicineView.h"

@implementation AddMedicine

@synthesize name, addTime, amount, amountLeft, amountLabel, amountLeftLabel, viewTime, refill, refillable, type, typeID, dosageType, medName, instructions, header3, header3title, addOrModifyMed, back, edit, viewMedicine, save, Cancel, timetable, doneTimeTable, addTimes, doAddTime, cancelAddTime, editNavigationBar, editOrDone, dosageNavigator, doneDosageNavigator, saving, saveInProgress, pleaseWait;
@synthesize mv, aD;

@synthesize editID, initialAmount, initialRefill, initialtypeID, initialAmountLeft, initialInstructions, initialName;

int timeTableActionSheet = 0;
int rowIndex = 0;
int editManager = 0;
int checkDIN;


int clockSetting = 0;
int dateSetting = 0;
int daySetting = 0;

int initialTimeTable = 0;
int finalTimeTable = 0;
int editTimeTable = -1;

NSString *finalName = @"";
NSString *finalRefill = @"";
NSString *finalInstructions = @"";
NSString *finalAmountLeft = @"";
NSString *finaltypeID = @"";
NSString *finalAmount = @"";

//Picker Synthesize
@synthesize pickerArray, dosagePicker, donePicker, addAnotherTime, doneTime, timeList;

/*Clicking on AddTime will display
 the picker to add a certain day that
 will iterate weekly*/ 
- (IBAction)AddTime:(id)sender{
    
    [medName resignFirstResponder];
    [amount resignFirstResponder];
    [amountLeft resignFirstResponder];
    [instructions resignFirstResponder];
    
    timetable.frame = CGRectMake(0, 44, 320, 205);
    
    addOrModifyMed.hidden = true;
    viewMedicine.hidden = true;
    editManager = 0;
    
    editNavigationBar.hidden = true;
    header3.hidden = true;
    addTimes.hidden = false;
    addAnotherTime.hidden = false;
    doneTime.hidden = false;
    
    [super setEditing:NO animated:YES];
    [timetable setEditing:NO animated:YES];
    [editOrDone setTitle:@"Modify Time Table"];
    [editOrDone setStyle:UIBarButtonItemStylePlain];
}

//Done Adding time
/*This will add the chosen time
 into an array; view time table view is also
 reloaded to be populated*/
- (IBAction)DoneAddingAnotherTime:(id)sender{
    
    addAnotherTime.timeZone = [NSTimeZone localTimeZone]; // check tomorrow
    
    NSDate *choice = [self.addAnotherTime date];
    NSTimeInterval time = floor([choice timeIntervalSinceReferenceDate]/60.0) * 60;
    choice = [NSDate dateWithTimeIntervalSinceReferenceDate:time];
    
    
    
    // [NSDate dateWithTimeIntervalSinceReferenceDate:time]
    
    //This will show the format - split and put into database.
    NSString *words = [[NSString alloc]initWithFormat:@"%@", choice];
    
    addAnotherTime.hidden = true;
    doneTime.hidden = true;
    header3title.title = @"Time Table";
    
    timetable.frame = CGRectMake(0, 44, 320, 372);
    editManager = -1;
    
    [self UnlockFields:YES];
    
    
    addTimes.hidden = true;
    header3.hidden = false;
    editNavigationBar.hidden = false;
    addOrModifyMed.hidden = true;
    viewMedicine.hidden = true;
    //Add this time into the list;
   // [timeList addObject:words]; //how about using addobject function
    
    finalTimeTable++;
    editTimeTable = 1;
    [timeList addObject:choice];

    [timetable reloadData];
    
    [words release];
}

//Makes tableview go back to original size when u cancel adding time.
- (IBAction)CancelAddingAnotherTime:(id)sender{

    addTimes.hidden = true;
    addAnotherTime.hidden = true;
    doneTime.hidden = true;
    header3.hidden = false;
    editNavigationBar.hidden = false;
    
    timetable.frame = CGRectMake(0, 44, 320, 372);
    editManager = -1;
    
    [self UnlockFields:YES];
    
    addOrModifyMed.hidden = true;
    viewMedicine.hidden = true;
}

//On Save; notifications will be created as reminders.
/*Create notifications for each of the times added*/
- (void)CreateLocalNotification:(NSDate *)medicineTime{
    UILocalNotification *LocalNotification = [[UILocalNotification alloc]init];
    LocalNotification.fireDate = medicineTime;
    LocalNotification.timeZone = [NSTimeZone defaultTimeZone];
    NSString *message = [[NSString alloc]initWithFormat:@"It's time to take \"%@\",\nInstructions: %@", medName.text, instructions.text];
    LocalNotification.alertBody = message;
    LocalNotification.alertAction = nil;
    LocalNotification.soundName = UILocalNotificationDefaultSoundName;
    LocalNotification.applicationIconBadgeNumber = 1;
    LocalNotification.repeatInterval = NSWeekCalendarUnit;
    
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];
    NSNumber *ID = [NSNumber numberWithInt:self.editID];
    
    [dictionary setObject:ID forKey:@"id"];
    [dictionary setObject:medName.text forKey:@"medName"];
    [dictionary setObject:instructions.text forKey:@"instructions"];
    LocalNotification.userInfo = dictionary;
    
    [[UIApplication sharedApplication] scheduleLocalNotification:LocalNotification];

    [LocalNotification release];
}

/*Load notifications when modifying a medicine*/
- (void)loadLocalNotifications{
    NSArray * notiflist = [[UIApplication sharedApplication] scheduledLocalNotifications];
    NSEnumerator *e = [notiflist objectEnumerator];
    UILocalNotification * notification;
    while (notification = [e nextObject]) {
        NSNumber *ID = [notification.userInfo objectForKey:@"id"];
        if([ID intValue] == editID){
            [timeList addObject:notification.fireDate];
        }
    }
    
}

/*when deleting a time from the time table 
 the notification is also deleted*/
- (void)removeLocalNotifications:(NSNumber *) medicineID{
    NSArray * notiflist = [[UIApplication sharedApplication] scheduledLocalNotifications];
    NSEnumerator *e = [notiflist objectEnumerator];
    UILocalNotification * notification;
    while (notification = [e nextObject]) {
        NSNumber *ID = [notification.userInfo objectForKey:@"id"];
        if([ID intValue] == editID){
            [[UIApplication sharedApplication] cancelLocalNotification:notification];
        }
    }
}

/*This will hide all the other fields; except the time table
 and displays all the added times*/
//This is view mode - no editing is permitted.
//all buttons are disabled except for Add/View times and no times can be added.
- (IBAction)ViewTime:(id)sender{

    if(medName.isEditing){
        if([self isNumeric:medName.text]){
            //look for in database
            [self dinNumber];
        }
    }
    
    [medName resignFirstResponder];
    [amount resignFirstResponder];
    [amountLeft resignFirstResponder];
    [instructions resignFirstResponder];
    
    addOrModifyMed.hidden = true;
    viewMedicine.hidden = true;
    name.hidden = true;
    medName.hidden = true;
    viewTime.hidden = true;
    type.hidden = true;
    dosageType.hidden = true;
    amount.hidden = true;
    amountLeft.hidden = true;
    typeID.hidden = true;
    refill.hidden = true;
    refillable.hidden = true;
    instructions.hidden = true;
    amountLabel.hidden = true;
    amountLeftLabel.hidden = true;
    
    dosagePicker.hidden = true;
    donePicker.hidden = true;
    
    doneTime.hidden = true;
    addAnotherTime.hidden = true;
    
    timetable.hidden = false;
    header3.hidden = false;
    editNavigationBar.hidden = false;
    header3title.title = @"Time Table";

    if (editManager!=-1) {
        editOrDone.enabled = NO;
    }
    else{
        editOrDone.enabled = YES;
    }
    
    timeTableActionSheet = 1;
}

/*hides the time tables and
 shows all other fields once again
 Step 1*/
- (IBAction)DoneViewTime:(id)sender{
    
    addOrModifyMed.hidden = false;
    viewMedicine.hidden = false;
    name.hidden = false;
    medName.hidden = false;
    viewTime.hidden = false;
    type.hidden = false;
    dosageType.hidden = false;
    amount.hidden = false;
    amountLeft.hidden = false;
    typeID.hidden = false;
    refill.hidden = false;
    refillable.hidden = false;
    instructions.hidden = false;
    amountLabel.hidden = false;
    amountLeftLabel.hidden = false;
    
    dosagePicker.hidden = true;
    donePicker.hidden = true;
    addAnotherTime.hidden = true;
    doneTime.hidden = true;
    
    timetable.hidden = true;
    header3.hidden = true;
    editNavigationBar.hidden = true;
    
    timeTableActionSheet = 0;
    
    [super setEditing:NO animated:YES];
    [timetable setEditing:NO animated:YES];
    [editOrDone setTitle:@"Modify Time Table"];
    [editOrDone setStyle:UIBarButtonItemStylePlain];
    
    [self UnlockFields:[self WillEdit]];
}

/*populate table cells with times from the array*/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    if (daySetting==0 && clockSetting==0) {
        [dateFormatter setDateFormat:@"EEEE, h:mm a"];
    }else
        if (daySetting==0 && clockSetting ==1) {
            [dateFormatter setDateFormat:@"EEEE, H:mm"];
        }else
            if (daySetting==1 && clockSetting==0) {
                [dateFormatter setDateFormat:@"EEE, h:mm a"];
            }else{
                [dateFormatter setDateFormat:@"EEE, H:mm"];
            }
    
    
    NSDateFormatter *yearFormatter = [[NSDateFormatter alloc]init];
    if (dateSetting==0) {
        [yearFormatter setDateFormat:@"MMM/dd/yyy"];
    }else{
        [yearFormatter setDateFormat:@"dd/MMM/yyy"];
    }
    
    
    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
    UITableViewCell *cell = [tableView
                             dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:SimpleTableIdentifier] autorelease];
    }
    rowIndex = [indexPath row];
    
    cell.textLabel.text = [[NSString alloc]initWithFormat:@"Every %@", [dateFormatter stringFromDate:[timeList objectAtIndex:rowIndex]]];
    cell.detailTextLabel.text = [[NSString alloc]initWithFormat:@"Starting on %@",[yearFormatter stringFromDate:[timeList objectAtIndex:rowIndex]]]; 
   // [timetable deselectRowAtIndexPath:indexPath animated:YES];
    // [[NSString alloc]initWithFormat:@"%@", choice]
    [dateFormatter release];
    return cell;
}

/*number of rows in the table view*/
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.timeList count];
}

/*An action sheet is displayed when a row is selected in the time table*/
- (void) tableView:(UITableView *) tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [timetable deselectRowAtIndexPath:indexPath animated:YES];
}

//If you want to delete time by swiping then delete; it would ask you
//if you delete time by pressing Modify time list... no alert is shown since more steps are required
//to delete time entry.
- (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle

forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSUInteger rowIndex = [indexPath row];
    if (editManager == -1) {
        if ([editOrDone.title isEqualToString:@"Modify Time Table"]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Are you sure?" message:@"This can not be undone" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
            [alert show];
            [alert release];
        }
        else{
            if (editingStyle == UITableViewCellEditingStyleDelete){
                finalTimeTable--;
                editTimeTable = 1;
                [timeList removeObjectAtIndex:rowIndex];
                [timetable reloadData];
                
                //[medicinelist removeObjectAtIndex:indexPath.row];
            } 
            else{
                if (editingStyle == UITableViewCellEditingStyleInsert)
                {
                }
            }
        }
    }
}

//go from view mode to edit mode
- (IBAction) EditTable:(id)sender{
    if(editManager==-1){
        if(self.editing)
        {
            [super setEditing:NO animated:YES];
            [timetable setEditing:NO animated:YES];
            [editOrDone setTitle:@"Modify Time Table"];
            [editOrDone setStyle:UIBarButtonItemStylePlain];
        }
        else{
            [super setEditing:YES animated:YES];
            [timetable setEditing:YES animated:YES];
            [editOrDone setTitle:@"Done"];
            [editOrDone setStyle:UIBarButtonItemStyleDone];
        }
    }
}

//Dosage Type Button
/*Dosage type shows what kind of medicine it is*/
- (IBAction)DosageType:(id)sender{
    
    if(medName.isEditing){
        if([self isNumeric:medName.text]){
            //look for in database
            [self dinNumber];
        }
    }
    
    [medName resignFirstResponder];
    [amount resignFirstResponder];
    [amountLeft resignFirstResponder];
    [instructions resignFirstResponder];
    
    addOrModifyMed.hidden = true;
    viewMedicine.hidden = true;
    name.hidden = true;
    medName.hidden = true;
    viewTime.hidden = true;
    type.hidden = true;
    dosageType.hidden = true;
    amount.hidden = true;
    amountLeft.hidden = true;
    typeID.hidden = true;
    refill.hidden = true;
    refillable.hidden = true;
    instructions.hidden = true;
    amountLabel.hidden = true;
    amountLeftLabel.hidden = true;
    dosageNavigator.hidden = false;
    
    dosagePicker.hidden = false;
    donePicker.hidden = false;
}

//Dosage Picker function
/*when done this changes the type ID
 according to the medicine type*/
- (IBAction)DoneDosagePicker:(id)sender{
    
    [medName resignFirstResponder];
    [amount resignFirstResponder];
    [amountLeft resignFirstResponder];
    [instructions resignFirstResponder];
    
    NSString *choice = [pickerArray objectAtIndex:[dosagePicker selectedRowInComponent:0]];
    if([choice isEqualToString:@"Pills"])
        typeID.text = @"capsules";
    else
        if([choice isEqualToString:@"Syrup"])
            typeID.text = @"ml";
        else
            if([choice isEqualToString:@"Powder"])
                typeID.text = @"g";
            else
                typeID.text = @"drops";
    
    dosagePicker.hidden = true;
    donePicker.hidden = true;
    dosageNavigator.hidden = true;
    
    addOrModifyMed.hidden = false;
    viewMedicine.hidden = false;
    name.hidden = false;
    medName.hidden = false;
    viewTime.hidden = false;
    type.hidden = false;
    dosageType.hidden = false;
    amount.hidden = false;
    amountLeft.hidden = false;
    typeID.hidden = false;
    refill.hidden = false;
    refillable.hidden = false;
    instructions.hidden = false;
    amountLabel.hidden = false;
    amountLeftLabel.hidden = false;
    
    [self UnlockFields:YES];
}

//Dosage Type Picker Set up
- (NSInteger) numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [pickerArray count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [pickerArray objectAtIndex:row];
}

//go back to medicine view from edit mode
- (void)ChangeView{
    MedicineView *mvObject = [[MedicineView alloc]initWithNibName:@"MedicineView" bundle:nil];
    self.mv = mvObject;
    [mvObject release];
    
    pleaseWait.hidden = true;
    saving.hidden = true;
    saveInProgress.hidden = true;
    [pleaseWait stopAnimating];
    
    mv.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:mv animated:YES];
}

/*On Save all notifications are created once again
 and times are saved; this is effective in case the user
 chooses to cancel; nothing gets saved
 Populates the database and updates the medicine fields in the database*/
- (IBAction)Save:(id)sender{
    
    //create notifications
    //[self CreateLocalNotification:choice];
    
    if([self CheckInputs]){
        
        pleaseWait.hidden = false;
        saving.hidden = false;
        saveInProgress.hidden = false;
        [pleaseWait startAnimating];
        Cancel.enabled = NO;
        save.enabled = NO;
        
        BOOL didModify = NO;
        
        sqlite3_stmt * statement;
        NSString * enforceForeignKey = @"PRAGMA foreign_keys = 1";
        const char * query_stmt = [enforceForeignKey UTF8String];
        if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK) {
            sqlite3_step(statement);
            if (sqlite3_errcode(aD.dbPointer) == SQLITE_OK) {
                sqlite3_finalize(statement);
            }
            else {
                //Couldn't enforce foreign key constraint.
            }
        }
        [enforceForeignKey release];
        
        /*@synthesize name, addTime, amount, amountLeft, viewTime, refill, refillable, type, tue_s, typeID, tuesday, thursday, thurs_s, dosageType, medName, mon_s, monday, instructions, step1, step2, header1, header2, save, sat_s, sun_s, sunday, saturday, wed_s, wedensday, fri_s, friday, currentStep, Cancel;*/
        
        NSString *strRefillable = [[NSString alloc]initWithFormat:@""];
        if(refill.isOn == true){
            strRefillable = @"1";
            finalRefill = @"true";
        }
        else{
            strRefillable = @"0";
            finalRefill = @"false";
        }
        
        NSString *medicine_type = instructions.text; //Specify the medicine type. Currently NYI in the GUI.
        NSString *medicine_name = medName.text;
        NSString *instructions_text = instructions.text;
        NSString *dosage_per_serving = amountLeft.text;
        NSString *dosage_type = [pickerArray objectAtIndex:[dosagePicker selectedRowInComponent:0]];
        
        
        finalName = medName.text;
        finaltypeID = typeID.text;
        finalAmount = amount.text;
        finalAmountLeft = amountLeft.text;
        finalInstructions = instructions.text;
        
        NSString *log_name;
        NSString *log_refill;
        NSString *log_typeID;
        NSString *log_amount;
        NSString *log_amountLeft;
        NSString *log_Instructions;
        NSString *log_timeTable;
        
        NSString *logChange;
        
        if (editID>0) {
            if (initialName.text != finalName) {
                log_name  = [[NSString alloc]initWithFormat:@"\n\n• You have changed the Name from %@ to %@.", initialName.text, finalName];
                didModify = YES;
            }else{
                log_name  = [[NSString alloc]initWithFormat:@""];
            }
            
            if (initialRefill.text != finalRefill) {
                if (refill.isOn == true){
                    log_refill = [[NSString alloc] initWithFormat: @"\n\n• You have changed the Refill State from No to Yes."];
                    didModify = YES;
                }
                else{
                    log_refill = [[NSString alloc] initWithFormat: @"\n\n• You have changed the Refill State from Yes to No."];
                    didModify = YES;
                }
            }
            else{
                log_refill = [[NSString alloc] initWithFormat: @""];
            }
            
            if (initialtypeID.text != finaltypeID){
                    log_typeID = [[NSString alloc] initWithFormat: @"\n\n• You have changed the Type from %@ to %@.", initialtypeID.text, finaltypeID];
                didModify = YES;
            }else{
                    log_typeID = [[NSString alloc] initWithFormat:@""];
            }
            
            if (initialInstructions.text != finalInstructions) {
                log_Instructions = [[NSString alloc] initWithFormat: @"\n\n• You have changed the Instructions of the medicine from %@ to %@.", initialInstructions.text, finalInstructions]; 
                didModify = YES;
            }else{
                log_Instructions = [[NSString alloc] initWithFormat:@""];
            }
            
            if (initialAmount.text != finalAmount) {
                log_amount = [[NSString alloc] initWithFormat: @"\n\n• You have changed the Amount from %@ to %@.", initialAmount.text, finalAmount];
                didModify = YES;
            }else{
                log_amount = [[NSString alloc] initWithFormat:@""];
            }
            
            if (initialAmountLeft.text != finalAmountLeft) {
                log_amountLeft = [[NSString alloc] initWithFormat: @"\n\n• You have changed the Amount Left from %@ to %@.", initialAmountLeft.text, finalAmountLeft];
                didModify = YES;
            }else{
                 log_amountLeft = [[NSString alloc] initWithFormat:@""];
            }
            
            if (initialTimeTable < finalTimeTable) {
                log_timeTable = [[NSString alloc]initWithFormat:@"\n\n• You have added some times to the Time Table."];
                didModify = YES;
            }else{
                if (initialTimeTable > finalTimeTable) {
                    log_timeTable = [[NSString alloc]initWithFormat:@"\n\n• You have deleted some times from the Time Table."];
                    didModify = YES;
                }else{
                    if (editTimeTable > -1) {
                        log_timeTable = [[NSString alloc]initWithFormat:@"\n\n• You have edited the Time Table."];
                        didModify = YES;
                    }else{
                        log_timeTable = [[NSString alloc]initWithFormat:@""];
                    }
                }
            }
            
            logChange = [[NSString alloc]initWithFormat:@"• Full Report •\n_______________________________%@%@%@%@%@%@%@\n_______________________________\n\n• End Of Report •",log_name, log_timeTable, log_typeID,  log_amount, log_amountLeft, log_refill,log_Instructions];
        }
        
        
        /*if([typeID.text isEqualToString:@"capsules"])
            dosage_type = @"Pills";
        else
            if([typeID.text isEqualToString:@"ml"])
                dosage_type = @"Syrup";
            else
                if([typeID.text isEqualToString:@"g"])
                    dosage_type = @"Powder";
                else
                    if([typeID.text isEqualToString:@"drops"])
                        dosage_type = @"Eye Drops"; */
        
        NSString *quantity_remaining= amount.text;
        
        //This is the SQL statement to add a medicine entry.
        NSString * queryString;
        if (editID == -1) { //Insertion mode
            queryString = [[NSString alloc]initWithFormat:@"INSERT INTO Medicine (medicine_type, medicine_name, refillable, instruction, dosage_per_serving, dosage_type, quantity_remaining) VALUES ('%@', '%@', '%@', '%@', '%@', '%@', '%@');", medicine_type, medicine_name, strRefillable,instructions_text, dosage_per_serving, dosage_type, quantity_remaining];
            
            //update logs medicine added on Time
        }
        else if (editID >= 0) { // editing mode
            queryString = [[NSString alloc]initWithFormat:@"UPDATE Medicine SET medicine_type='%@', medicine_name='%@', refillable='%@', instruction='%@', dosage_per_serving='%@', dosage_type='%@', quantity_remaining='%@' WHERE id=%d;", medicine_type, medicine_name, strRefillable, instructions_text, dosage_per_serving, dosage_type, quantity_remaining, editID];
            
            //update logs medicine modified on time
        }
        query_stmt = [queryString UTF8String];
        if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
            sqlite3_step(statement);
            if (sqlite3_errcode(aD.dbPointer) == SQLITE_DONE){
                sqlite3_finalize(statement);
                
                NSDate *saveDate = [NSDate date];
                
                //NSTimeInterval time = floor([choice timeIntervalSinceReferenceDate]/60.0) * 60;
                //saveDate = [NSDate dateWithTimeIntervalSinceReferenceDate:time];
                
                if(self.editID == -1){ // this was an insertion, so we can (and need to) retrieve the id of the medicine we just added.
                    
                    logChange = @"";
                    
                    NSString *queryLogString = [[NSString alloc]initWithFormat:@"INSERT INTO MedicineLog (medicine_name, log_change, status, time) VALUES ('%@',' ', 'Added', '%@');", medicine_name, saveDate];
                    
                    query_stmt = [queryLogString UTF8String];
                    if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
                        sqlite3_step(statement);
                        if (sqlite3_errcode(aD.dbPointer) == SQLITE_DONE){
                            sqlite3_finalize(statement);
                        }
                    }
                    
                    
                    self.editID = sqlite3_last_insert_rowid(aD.dbPointer);
                }else{
                    
                    if (![logChange isEqualToString:@""]) {
                        NSString *queryLogModifyString = [[NSString alloc]initWithFormat:@"INSERT INTO MedicineLog (medicine_name, log_change, status, time) VALUES ('%@','%@', 'Modified', '%@');", medicine_name, logChange, saveDate];                 
                        
                        query_stmt = [queryLogModifyString UTF8String];
                        if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
                            sqlite3_step(statement);
                            if (sqlite3_errcode(aD.dbPointer) == SQLITE_DONE){
                                sqlite3_finalize(statement);
                            }
                        }
                    }
                    
                    editTimeTable = -1;
                    [log_name release];
                    [log_refill release];
                    [log_Instructions release];
                    [log_typeID release];
                    [log_amount release];
                    [log_amountLeft release];
                    [log_timeTable release];
                    [logChange release];
                }
                
                [self performSelector:@selector(ChangeView) withObject:nil afterDelay:1];
                
                [self removeLocalNotifications:(NSNumber *) editID]; // remove current notifications for this medicine (they will be recreated)
                
                //save the following variables to database.
                for (int i = 0; i < [timeList count]; i++) {
                    [self CreateLocalNotification:[timeList objectAtIndex:i]];
                }
                
                //add status & date for medicine added. (edit or added)
                
                
            }
            else {
                // Pop up message for SQL error.
                
                pleaseWait.hidden = true;
                saving.hidden = true;
                saveInProgress.hidden = true;
                [pleaseWait stopAnimating];
                
                Cancel.enabled = YES;
                save.enabled = YES;
                
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Unsuccessful" message:@"Can not Add Entry" delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];
                [alert show];
                [alert release];
            }
        }
        [queryString release];
    }
}

/*Check all inputs are filled*/
- (BOOL)CheckInputs{
    UIAlertView *alert;
    BOOL success = false;
    
    if ([medName.text isEqualToString:@""]) {
        alert = [[UIAlertView alloc]initWithTitle:@"Unsuccessful" message:@"Please enter a Medicine Name" delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];

        [alert show];
        [alert release];
        success = false;
    }
    else{
        if ([amountLeft.text isEqualToString:@""]) {
            alert = [[UIAlertView alloc]initWithTitle:@"Unsuccessful" message:@"Please enter amount left." delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];

            [alert show];
            [alert release];
            success = false;
        }
        else{
            if ([amount.text isEqualToString:@""]) {
                alert = [[UIAlertView alloc]initWithTitle:@"Unsuccessful" message:@"Please enter the amount per dosage." delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];
                
                [alert show];
                [alert release];
                success = false;
            }
            else{
                success = true;
            }
        }
    }
    
    return success;
}

//Checks all fields and makes save button More red (done style) iphone default to confirm its available to save successfully
- (void)CheckInputsWithoutNotifying{

    if (!([medName.text isEqualToString:@""] || [amount.text isEqualToString:@""] || [amountLeft.text isEqualToString:@""])) {
        [save setStyle:UIBarButtonItemStyleDone];
    }
    else{
        [save setStyle:UIBarButtonItemStyleBordered];
    }
}


- (IBAction)InsertDate:(id)sender {
    
    //    NSMutableArray 
    /*NSArray *dayOfWeek = [[NSArray alloc]initWithObjects:mon_s.on, tue_s.on, wed_s.on, thurs_s.on, fri_s.on, sat_s.on, sun_s.on, nil];
    sqlite3_stmt * statement;
    NSString * queryString;
    const char * query_stmt;
    BOOL quit = NO;
    //For each time and day of the week....
    for (int i = 0; i < [dayOfWeek count]; i++) {
        if ([dayOfWeek objectAtIndex:i] == NO) {
            continue;
        }
        for (int j = 0; j < [timeList count]; i++) { 
            queryString = [[NSString alloc]initWithFormat:@"INSERT INTO Date (associated_medicine, time) VALUES (1, '1111')"];
            query_stmt = [queryString UTF8String];
            if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK) {
                sqlite3_step(statement);
                if (sqlite3_errcode(aD.dbPointer) != SQLITE_OK) {
                    quit = YES;
                }
            }
            [queryString release];
            if (quit == YES) {
                break;
                //Add an alert here to see if time's added successfully [DEBUG]
            }
        }
        if (quit == YES) {
            break;
        }
    }
    if (quit == NO) {
        sqlite3_finalize(statement);
    }
    [dayOfWeek release];*/
}

/*Cancel will discard all changes;
 nothing will get saved*/
- (IBAction)Cancel:(id)sender{
    //Call Action Sheet
    
    
    [medName resignFirstResponder];
    [amount resignFirstResponder];
    [amountLeft resignFirstResponder];
    [instructions resignFirstResponder];
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"Your work will be lost. Are you sure you want to Cancel" delegate:self cancelButtonTitle:@"No" destructiveButtonTitle:@"Yes" otherButtonTitles:nil];
    
    [actionSheet showInView:self.view];
    [actionSheet release];    
}

//going from view mode to edit mode
//will make all placeholders active and text will be places.
- (IBAction)Edit:(id)sender{
    
    medName.text = medName.placeholder;
    medName.placeholder = @"";
    amount.text = amount.placeholder;
    amount.placeholder = @"";
    amountLeft.text = amountLeft.placeholder;
    amountLeft.placeholder = @"";
    instructions.text = instructions.placeholder;
    instructions.placeholder = @"";
    [dosageType setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    editManager = -1;
    //enable all textfields and show addormodify header.
    [self UnlockFields:[self WillEdit]];
    viewMedicine.hidden = true;
    addOrModifyMed.hidden = false;
    
    [self CheckInputsWithoutNotifying];
}

//go back to medicine view from Edit Mode
- (IBAction)Back:(id)sender{
    [medName resignFirstResponder];
    [amount resignFirstResponder];
    [amountLeft resignFirstResponder];
    [instructions resignFirstResponder];
    
    MedicineView *mvObject = [[MedicineView alloc]initWithNibName:@"MedicineView" bundle:nil];
    self.mv = mvObject;
    [mvObject release];
    
    mv.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:mv animated:YES];
}

//Action Sheet Function
/*Action sheet will either cancel or remove a medicine from table view
 this works according to what timetableActionSheet is;
 timeTableActionSheet = 0 : Cancel
 timeTableActionSheet = 1 : remove time from timetable*/
- (void) actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex != [actionSheet cancelButtonIndex]) //Go back to medicine view
    {
        if(timeTableActionSheet == 0){
            MedicineView *mvObject = [[MedicineView alloc]initWithNibName:@"MedicineView" bundle:nil];
            self.mv = mvObject;
            [mvObject release];
            
            mv.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
            [self presentModalViewController:mv animated:YES];
        }
    }
}

//removing a time entry
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        finalTimeTable--;
        editTimeTable = 1;
        [timeList removeObjectAtIndex:rowIndex];
        [timetable reloadData];
    }
}

//Support Functions
/*try and find DIN number from database*/
- (void)dinNumber{
    NSString *loadDIN = [[NSString alloc]initWithFormat:@"SELECT desc FROM dinlist WHERE din='%@';", medName.text];
    
    sqlite3_stmt * statement;
    const char * query_stmt;
    
    query_stmt = [loadDIN UTF8String];
    if (sqlite3_prepare_v2(dinDB, query_stmt, -1, &statement, NULL) == SQLITE_OK){
        
        if (sqlite3_step(statement) == SQLITE_ROW){
            NSString *medicineName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
            medicineName = [[NSString alloc]initWithFormat:@"%@%@",[medicineName substringToIndex:1],[[medicineName substringFromIndex:1]lowercaseString]];
            medName.text = medicineName;
        }
        else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Invalid DIN" message:@"DIN cannot be found in database." delegate:self cancelButtonTitle:@"ok" otherButtonTitles: nil];
            
            [alert show];
            [alert release];
        }
    }
}

//checks if medicine is added or viewed.
//this decides whether the filed should be locked or unlocked
- (BOOL)WillEdit{
    if (editManager>=0) {
        return false;
    }else{
        return true;
    }
}

//unlock fields according to the passed boolean (enable)
//lock fields when viewing
//unlock fields when editing
- (void)UnlockFields:(BOOL)enable{
    
    if (enable) {
        medName.enabled = true;
        dosageType.enabled = true;
        addTime.enabled = true;
        amount.enabled = true;
        amountLeft.enabled = true;
        instructions.enabled = true;
        refill.enabled = true;
        addTime.enabled = YES;
        
        viewMedicine.hidden = true;
        addOrModifyMed.hidden = false;
    }else{
        medName.enabled = false;
        dosageType.enabled = false;
        addTime.enabled = false;
        amount.enabled = false;
        amountLeft.enabled = false;
        instructions.enabled = false;
        refill.enabled = false;
        addTime.enabled = NO;
        
        viewMedicine.hidden = false;
        addOrModifyMed.hidden = true;
    }

}

/*Checks if the medicine name is all numbers;
 if so, it checks if its an available DIN number*/
- (BOOL)isNumeric:(NSString *) s{
    NSScanner *sc = [NSScanner scannerWithString: s];
    if ( [sc scanFloat:NULL] )
    {
        return [sc isAtEnd];
    }
    return NO;
}

/*Tapping the background will get rid of the keyboard*/
- (IBAction)tapBackground:(id)sender{
    
    if(medName.isEditing){
        if([self isNumeric:medName.text]){
            checkDIN = 1;
            //look for in database
            [self dinNumber];
        }
    }
    
    [medName resignFirstResponder];
    [amount resignFirstResponder];
    [amountLeft resignFirstResponder];
    [instructions resignFirstResponder];
}

/*Tapping Done on Keyboard will discard the keyboard of the current text field*/
- (IBAction)doneKeyboard:(id)sender{
    
    if(medName.isEditing){
        if([self isNumeric:medName.text]){
            checkDIN = 1;
            //look for in database
            [self dinNumber];
        }
    }
    
    [sender resignFirstResponder];
}

/*Raise the view to prevent the keyboard overlaying the text fields*/
- (IBAction)textFieldDidBeginEditing:(UITextField *)textField
{
    if ((amount.isEditing || amountLeft.isEditing) && checkDIN==0) {
        if([self isNumeric:medName.text]){
            [self dinNumber];
            checkDIN = 1;
        }
    }
    
    [self animateTextField: textField up: YES];
}


- (IBAction)textFieldDidEndEditing:(UITextField *)textField
{
    [self animateTextField: textField up: NO];
    [self CheckInputsWithoutNotifying];
}

- (void) animateTextField: (UITextField *) textField up: (BOOL) up
{
    const int movementDistance = 165; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed
    
    int movement = (up ? -movementDistance : movementDistance);
    
    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}

- (IBAction)textFieldDidBeginEditingName:(UITextField *)textField
{
    if (medName.isEditing) {
        checkDIN = 0;
    }
    
    [self animateTextFieldName: textField up: YES];
}


- (IBAction)textFieldDidEndEditingName:(UITextField *)textField
{
    [self animateTextFieldName: textField up: NO];
    [self CheckInputsWithoutNotifying];
}

- (void) animateTextFieldName: (UITextField *) textField up: (BOOL) up
{
    const int movementDistance = 60; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed
    
    int movement = (up ? -movementDistance : movementDistance);
    
    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}
//end of animation

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        editID = -1; // -1 means that we are adding a new medicine entry. If this is not the case, a call to
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

/*Load Medicines if the medicine is to be modified*/
- (void)loadMedicineByID {
    if(editID >= 0){
        aD = [[UIApplication sharedApplication] delegate];
        
        sqlite3_stmt * statement;
        const char * query_stmt;
        
        NSString *loadMed = [[NSString alloc]initWithFormat:@"SELECT medicine_type, medicine_name, refillable, instruction, dosage_per_serving, dosage_type, quantity_remaining FROM Medicine WHERE id=%d;", editID];
        
        query_stmt = [loadMed UTF8String];
        if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
            
            if (sqlite3_step(statement) == SQLITE_ROW){
                //Todo Set a field for Medicine Type
                //Todo Get dosage type from dosage picker
                medName.text = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
                if (sqlite3_column_int(statement, 2) == 0){
                    refill.on = false;
                    initialRefill.text = @"false";
                } 
                else {
                    refill.on = true;
                    initialRefill.text = @"true";
                }
                instructions.text = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 3)];
                amountLeft.text = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 4)];
                typeID.text = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 5)];
                amount.text = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 6)];
                
                if ([typeID.text isEqualToString:@"Pills"])
                    [dosagePicker selectRow:0 inComponent:0 animated:YES];
                else
                    if([typeID.text isEqualToString:@"Syrup"])
                        [dosagePicker selectRow:1 inComponent:0 animated:YES];
                    else
                        if([typeID.text isEqualToString:@"Powder"])
                            [dosagePicker selectRow:2 inComponent:0 animated:YES];
                        else
                            if([typeID.text isEqualToString:@"Eye Drops"])
                                [dosagePicker selectRow:3 inComponent:0 animated:YES];
                
                [self DoneDosagePicker:dosagePicker];
                [self UnlockFields:NO];
            }
            
            
        }

        amount.text = [amount.text stringByReplacingOccurrencesOfString:@".0" withString:@""];
        amountLeft.text = [amountLeft.text stringByReplacingOccurrencesOfString:@".0" withString:@""];
        
        initialName.text = medName.text;
        initialtypeID.text = typeID.text;
        initialAmount.text = amount.text;
        initialAmountLeft.text = amountLeft.text;
        initialInstructions.text = instructions.text;
        
        medName.placeholder = medName.text;
        medName.text = @"";
        amount.placeholder = amount.text;
        amount.text = @"";
        amountLeft.placeholder = amountLeft.text;
        amountLeft.text = @"";
        instructions.placeholder = instructions.text;
        instructions.text = @"";
        [dosageType setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];
    }
}

#pragma mark - View lifecycle

/*Load Database, arrays and notifications*/
- (void)viewDidLoad
{
    aD = [[UIApplication sharedApplication] delegate];
    
    editManager = editID;
    
    [self UnlockFields:[self WillEdit]];
    
     
    NSArray *arr = [[NSArray alloc]initWithObjects:@"Pills", @"Syrup", @"Powder", @"Eye Drops", nil];
    self.pickerArray = arr;
    
    [arr release];
    
    NSString *dinDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"din.db"];
    sqlite3_open([dinDBPath UTF8String], &dinDB);
    
    NSMutableArray *timeListObject = [[NSMutableArray alloc]init];
    self.timeList = timeListObject;
    
    [timeListObject release];
    
    //    [dinDBPath release];
    //self.timeList = [NSMutableArray alloc];
    //[self.timeList init];
    //[self.timeList addObject:];
//    NSCalendar *cal = [NSCalendar currentCalendar];
//    NSDateComponents *components = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|//NSDayCalendarUnit) fromDate:[NSDate date] fromDate:<#(NSDate *)#>
    NSDate *today = [NSDate date];
    
    [addAnotherTime setMinimumDate:today];
    
    
    [self loadLocalNotifications];
    initialTimeTable = [timeList count];
    finalTimeTable = initialTimeTable;
    
    
    sqlite3_stmt *statement;
    const char * query_stmt;
    NSString *loadSettings= @"SELECT clock_setting, date_setting, day_setting FROM Settings;";
    query_stmt = [loadSettings UTF8String];
    
    if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
        
        if (sqlite3_step(statement) == SQLITE_ROW){
            clockSetting = sqlite3_column_int(statement, 0);
            dateSetting = sqlite3_column_int(statement, 1);
            daySetting = sqlite3_column_int(statement, 2);
            
        }
    }
    
    [loadSettings release];
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

/*release all outlets*/
- (void) dealloc{
    
    [mv release];
    [aD release];
    
    [initialName release];
    [initialRefill release];
    [initialtypeID release];
    [initialInstructions release];
    [initialAmountLeft release];
    [initialAmount release];
    
    [pickerArray release];
    [dosagePicker release];
    [donePicker release];
    
    [addAnotherTime release];
    [doneTime release];
    [timeList  release];
    
    [medName release];
    [amount release];
    [amountLeft release];
    [instructions release];
    
    [viewTime release];
    [dosageType release];
    [refill  release];
    [header3 release];
    [header3title release];
    [doneTimeTable release];
    [addTime release];
    
    [addOrModifyMed release];
    [Cancel release];
    [save release];
    
    [viewMedicine release];
    [back release];
    [edit release];
    
    [addTimes release];
    [doAddTime release];
    [cancelAddTime release];
    
    [editNavigationBar release];
    [editOrDone release];
    
    [dosageNavigator release];
    [doneDosageNavigator release];
    
    [name release];
    [type release];
    [amountLeft release];
    [amountLeftLabel release];
    [typeID release];
    [refillable release];
    
    [timetable release];
    
    [saving release];
    [pleaseWait release];
    [saveInProgress release];
    
    [super dealloc];
}

@end
